package com.zhj.estest.client.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexAction;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.AliasMetaData;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ESTest_Index_Client {
    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200,"http"))
        );

        // 创建索引
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("people");
        CreateIndexResponse createIndexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);

        boolean createAcknowledged = createIndexResponse.isAcknowledged();
        if (createAcknowledged) {
            System.out.println("创建索引成功！");
        } else {
            System.out.println("创建索引失败！");
        }

        // 查询索引
        GetIndexRequest getIndexRequest = new GetIndexRequest("user");
        GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        Map<String, List<AliasMetaData>> aliases = getIndexResponse.getAliases();
        System.out.println(aliases);
        System.out.println(getIndexResponse.getSettings());
        System.out.println(getIndexResponse.getMappings());

        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("people");
        AcknowledgedResponse delete = esClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        boolean deleteAcknowledged = delete.isAcknowledged();
        if (deleteAcknowledged) {
            System.out.println("删除索引成功！");
        } else {
            System.out.println("删除索引失败！");
        }

        // 关闭客户端
        esClient.close();
    }
}
